package com.surfilter.msmp.web.system.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.surfilter.msmp.common.model.MDict;
import com.surfilter.msmp.common.service.MDictService;
import com.surfilter.msmp.web.common.JsonResult;
import com.surfilter.msmp.web.common.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.annotation.RequiresPermissions;

import java.util.Date;
import java.util.List;

/**
 * 描述：字典管理
 * 作者：Msh
 * 时间：2019-11-11 10:20:58
 */

@Api(value = "字典管理", tags = "dict")
@RequestMapping("${api.version}/dict")
@RestController
public class MDictController {

    Logger logger = LoggerFactory.getLogger(MDictController.class);

    @Autowired
    private MDictService mDictService;

    @RequiresPermissions("get:/v1/dict")
    @ApiOperation(value = "分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "搜索关键字", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "access_token", value = "令牌", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping()
    public PageResult<MDict> list(Integer page, Integer limit, MDict mDict) {
        // 筛选结果
        if (page == null) {
            page = 0;
        }
        if (limit == null) {
            limit = 10;
        }
        Page<MDict> dictPage = new Page<>(page, limit);
        EntityWrapper<MDict> dictEntityWrapper = new EntityWrapper<>();

       if(StringUtils.isNotBlank(mDict.getmType())) {
           dictEntityWrapper.where("m_type='" + mDict.getmType() + "'");
        }

        if(StringUtils.isNotBlank(mDict.getmKey())) {
            dictEntityWrapper.where("m_key='" + mDict.getmKey() + "'");
        }

        if(StringUtils.isNotBlank(mDict.getmValue())) {
            dictEntityWrapper.where("m_value='" + mDict.getmValue() + "'");
        }

        dictEntityWrapper.orderBy("gmt_create", true);
        Page<MDict> dictPageRes = mDictService.selectPage(dictPage, dictEntityWrapper);
        return new PageResult<>(dictPageRes.getRecords(), dictPageRes.getTotal());
    }

    @RequiresPermissions("post:/v1/dict")
    @ApiOperation(value = "新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access_token", value = "令牌", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping()
    public JsonResult insert(MDict mDict){
        try {
            EntityWrapper<MDict> entityWrapper = new EntityWrapper<>();
            entityWrapper.where("m_type='"+mDict.getmType()+"'");
            entityWrapper.where("m_key='"+mDict.getmKey()+"'");
            List<MDict> list = mDictService.selectList(entityWrapper);
            if(list != null && list.size()>0){
               return JsonResult.error("新增字典信息已存在，新增失败");
            }
          mDict.setGmtCreate(new Date());  //更新时间
          mDict.setGmtModified(new Date()); //修改时间
          mDictService.insert(mDict);
          return JsonResult.ok("新增成功");
        }catch (Exception e){
            logger.error("系统异常:"+e);
            return JsonResult.error("系统异常，新增失败");
        }
    }

    @RequiresPermissions("post:/v1/dict/update")
    @ApiOperation(value="更新")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access_token", value = "令牌", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping("/update")
    public JsonResult update(MDict mDict){
        try {
            MDict resMDic = mDictService.selectById(mDict.getId());
            if(resMDic != null && resMDic.getId() != null){
                mDict.setGmtModified(new Date());
                mDictService.updateById(mDict);
                return JsonResult.ok("更新成功");
            }else{
                return JsonResult.error("更新数据不存在，更新失败");
            }
        }catch (Exception e){
            logger.error("系统异常:"+e);
            return JsonResult.error("系统异常，更新失败");
        }

    }

    @RequiresPermissions("delete:/v1/dict/{id}")
    @ApiOperation(value = "删除", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "access_token", value = "令牌", required = true, dataType = "String", paramType = "form")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Integer id) {
        if (mDictService.deleteById(id)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

    @RequiresPermissions("post:/v1/dict/find")
    @ApiOperation(value = "获取字典信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "access_token", value = "令牌", required = true, dataType = "String", paramType = "form")
    })
    @PostMapping("/find")
    public List<MDict> selectBywhere(MDict mDict){

        EntityWrapper<MDict> entityWrapper = new EntityWrapper<>();
        entityWrapper.where("m_type='"+mDict.getmType()+"'");
        return mDictService.selectList(entityWrapper);
    }

}
